/**
 * 日志工具
 * 生产环境自动清理console输出
 */

const isDevelopment = import.meta.env.DEV
const isProduction = import.meta.env.PROD

type LogLevel = 'log' | 'info' | 'warn' | 'error' | 'debug'

interface Logger {
  log: (...args: any[]) => void
  info: (...args: any[]) => void
  warn: (...args: any[]) => void
  error: (...args: any[]) => void
  debug: (...args: any[]) => void
  group: (...args: any[]) => void
  groupEnd: () => void
}

// 开发环境使用原生console
const consoleProxy: Logger = {
  log: (...args) => console.log(...args),
  info: (...args) => console.info(...args),
  warn: (...args) => console.warn(...args),
  error: (...args) => console.error(...args),
  debug: (...args) => console.debug(...args),
  group: (...args) => console.group(...args),
  groupEnd: () => console.groupEnd(),
}

// 生产环境的空实现
const emptyProxy: Logger = {
  log: () => {},
  info: () => {},
  warn: () => {},
  error: (...args) => {
    // 生产环境保留error，但可以发送到监控系统
    if (typeof window !== 'undefined' && (window as any).reportError) {
      ;(window as any).reportError(...args)
    }
  },
  debug: () => {},
  group: () => {},
  groupEnd: () => {},
}

// 导出logger实例
const logger: Logger = isDevelopment ? consoleProxy : emptyProxy

export default logger

/**
 * 分级日志输出
 */
export const createLogger = (level: LogLevel = 'log') => {
  return (...args: any[]) => {
    logger[level](...args)
  }
}

// 性能监控
export const perf = {
  mark(name: string) {
    if (isDevelopment && performance.mark) {
      performance.mark(name)
    }
  },

  measure(name: string, startMark: string, endMark?: string) {
    if (isDevelopment && performance.measure) {
      try {
        performance.measure(name, startMark, endMark)
        const measure = performance.getEntriesByName(name)[0]
        console.log(`⏱️ Performance [${name}]:`, `${measure.duration.toFixed(2)}ms`)
      } catch (e) {
        console.warn('Performance measure failed:', e)
      }
    }
  },
}
